const express = require("express");
const router = express.Router();
const { v1: uuidV1 } = require("uuid");
var bodyParser = require("body-parser");

// 创建application/json 解析器
var jsonParser = bodyParser.json();

let connectDAO = require("../connect.js");
async function dbTrainInfo(sql, processData) {
  //processData为回调方法
  await connectDAO.queryDataBySQL(sql, processData);
}
// Blog账号注册
router.post("/register", jsonParser, function (req, res) {
  // 定义初始化返回信息
  const { username, password } = req.body;
  if (username && password) {
    //读
    const sql = `SELECT username FROM userInfo where username = '${username}'`;
    dbTrainInfo(sql, processData);
    //result为查询返回的结果
    function processData(result) {
      let data = JSON.parse(JSON.stringify(result));
      data = data[0];
      // 判断是否已有账号
      if (data) {
        message.msg = "该账号已被注册";
        message.code = 300;
        res.send(message);
        return;
      } else {
        const userDefalut = {
          avatarUrl:
            "https://img.zcool.cn/community/01b91e5d368512a80120695c617f59.jpg@1280w_1l_2o_100sh.jpg",
          nickname: "无名",
          city: "哪里人",
          sex: "man",
          birthday: "2000-01-01",
          university: "哪个学校毕业的",
          autograph: "这家伙很懒，还不写点东西",
          backgroundUrl:
            "https://img.zcool.cn/community/019e57623d72700002c3290fbab43f.jpg@520w_390h_1c_1e_2o_100sh.jpg",
        };
        const registerTime = parseInt(new Date().getTime() / 1000);
        const insertsql = `INSERT INTO userInfo VALUES ('${uuidV1()}', '${username}','${password}','${
          userDefalut.avatarUrl
        }','${userDefalut.nickname}','${userDefalut.city}','${
          userDefalut.sex
        }','${userDefalut.birthday}','${userDefalut.university}','${
          userDefalut.autograph
        }','${
          userDefalut.backgroundUrl
        }','0,0,0,${registerTime}',0,'[]','[]','[]')`;
        connectDAO
          .queryDataBySQL(insertsql)
          .then((data) => {
            res.send({ code: 200, msg: "注册成功" });
          })
          .catch((err) => {
            res.send({ code: 201, msg: "注册失败，请重试！" });
          });
      }
    }
  } else {
    message.msg = "参数错误";
    message.code = 400;
    res.send(message);
  }
});

// Blog账号登陆
router.post("/login", jsonParser, function (req, res) {
  let message = {};
  // 定义初始化返回信息
  const { username, password, code } = req.body;
  //读取
  const sql = `SELECT * FROM userInfo where username = '${username}'`;
  dbTrainInfo(sql, processData);
  //result为查询返回的结果
  function processData(result) {
    let data = JSON.parse(JSON.stringify(result));
    data = data[0];
    // 判断是否已有账号
    if (data && (code ? data.code == password : data.password == password)) {
      if(data.status == 0){
        message.msg = "账号已锁定，请联系管理员";
        message.code = 300;
        res.send(message);
        return
      }
      res.status(200);
      message.msg = "登陆成功";
      message.code = 200;
      delete data.password;
      const accountInfo = data.accountInfo.split(",");
      const obj = {
        lv: accountInfo[0],
        follows: accountInfo[1],
        fans: accountInfo[2],
        registerTime: accountInfo[3],
      };
      data.accountInfo = obj;
      message.userInfo = data;
      res.send(message);
    } else if (data) {
      message.code = 300;
      if (!code) {
        data.password != password ? (message.msg = "密码错误") : "";
      } else {
        data.code != password ? (message.msg = "验证码错误") : "";
      }
      res.send(message);
    } else {
      message.msg = "账号不存在";
      message.code = 400;
      res.send(message);
    }
  }
});

// 获取验证码
let time;
router.get("/getCode", function (req, res) {
  const { username } = req.query;
  const sql = `SELECT username FROM userInfo where username = '${username}'`;
  dbTrainInfo(sql, processData);
  function processData(result) {
    let data = JSON.parse(JSON.stringify(result));
    data = data[0];
    if (data) {
      const VerificationCode = Math.random().toFixed(6).slice(-6);
      res.send(VerificationCode);
      connectDAO.queryDataBySQL(
        `UPDATE userInfo SET VerificationCode = '${VerificationCode}' WHERE username = '${username}'`
      );
      clearTimeout(time);
      time = setTimeout(() => {
        connectDAO.queryDataBySQL(
          `UPDATE userInfo SET VerificationCode = 0 WHERE username = '${username}'`
        );
      }, 60000);
    } else {
      res.send("没有此账号，请先注册");
    }
  }
});

// 修改用户信息
router.post("/changeuserInfo", jsonParser, function (req, res) {
  const { userId, changeInfo } = req.body;
  const arr = Object.keys(changeInfo);
  for (let i = 0; i < arr.length; i++) {
    connectDAO.queryDataBySQL(
      `UPDATE userInfo SET  ${arr[i]} = '${
        changeInfo[arr[i]]
      }' WHERE id = '${userId}'`
    );
  }
  res.send({
    code: 200,
    msg: "修改成功",
  });
});

// 获取指定用户信息、名片
router.get("/getUser", function (req, res) {
  dbTrainInfo(
    `SELECT id,nickname,accountInfo,autograph,avatarUrl,backgroundUrl from userInfo WHERE id = '${req.query.id}';`,
    (result) => {
      res.send({
        code: 200,
        msg: "获取成功",
        result: JSON.parse(JSON.stringify(result))[0],
      });
    }
  );
});

router.get("/get_resume", function (req, res) {
  const { password } = req.query;
  dbTrainInfo(`SELECT password from resume;`, (result) => {
    if (password == JSON.parse(JSON.stringify(result))[0].password) {
      res.send({ code: 200, msg: "获取成功" });
    } else {
      res.send({ code: 201, msg: "密码错误" });
    }
  });
});

router.get("/get_collection", function (req, res) {
  const { userId } = req.query;
  dbTrainInfo(
    `SELECT collection_art from userInfo where id = '${userId}';`,
    (result) => {
      let collection_artArr = result[0].collection_art;
      collection_artArr = JSON.parse(collection_artArr);
      connectDAO.queryDataBySQL("SELECT * from articles where id IN" +"(\'" + collection_artArr.join("','") + "\');",(data)=>{
        res.send({ code: 200, msg: "获取成功", data });
      }).catch((err)=>{
        res.send({code:500, msg: "获取失败" })
      })
    }
  );
});

// 获取所有账号信息列表（管理台）
router.get("/get_userList",function (req,res) {
  const {searchAccountText} = req.query
  const sql = searchAccountText ? `SELECT * from userInfo where username LIKE '${searchAccountText}%';` : `SELECT * from userInfo;`
  dbTrainInfo(sql, (result) => {
    res.send({ code: 200, msg: "获取成功", result })
  });
})

// 修改账号状态
router.post("/change_status",function (req,res){
  let { userId,status } = req.body;
  status = status == 1 ?  0 :  1
  connectDAO.queryDataBySQL(`UPDATE userInfo SET status = ${status} WHERE id = '${userId}'`).then(()=>{
    res.send({
      code: 200,
      msg: "修改成功",
    });
  })
  
})

module.exports = router;
